//
//  ProfessionalViewController.m
//  Finance
//
//  Created by cheng xiang on 13-4-2.
//  Copyright (c) 2013年 cheng xiang. All rights reserved.
//

#import "ProfessionalViewController.h"
#import "CustomTableViewCell.h"
//#import "ASINetworkQueue.h"
#import "AppDelegate.h"
#import "AnalysisJson.h"
#import "MultiThreading.h"
@interface ProfessionalViewController ()

@end

@implementation ProfessionalViewController
@synthesize vedioTable;
@synthesize  dataarray;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    //显示专家视频信息
    CGRect frameRect = self.view.frame;
    self.vedioTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, frameRect.size.width, frameRect.size.height) style:UITableViewStylePlain];
    self.vedioTable.dataSource = self;
    self.vedioTable.delegate = self;
    [self.view addSubview:self.vedioTable];
    
//    downloadQueue = [[ASINetworkQueue alloc] init];
//    [downloadQueue reset];
//    [downloadQueue setShowAccurateProgress:YES];
//    [downloadQueue go];
    
    downloadPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
	//初始化临时文件路径
	NSString *folderPath = [downloadPath stringByAppendingPathComponent:@"temp"];
	//创建文件管理器
	NSFileManager *fileManager = [NSFileManager defaultManager];
	//判断temp文件夹是否存在
	BOOL fileExists = [fileManager fileExistsAtPath:folderPath];
	
	if (!fileExists)
    {//如果不存在说创建,因为下载时,不会自动创建文件夹
		[fileManager createDirectoryAtPath:folderPath
               withIntermediateDirectories:YES
                                attributes:nil
                                     error:nil];
    }
    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleBordered target:self action:@selector(goReturn)];
    [leftItem setBackgroundImage:[UIImage imageNamed:@"btn.png"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [leftItem setBackgroundImage:[UIImage imageNamed:@"btn.png"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    UIColor* bk = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"beij.png"]];
    
    [self.vedioTable setBackgroundColor:bk];
    
    dataarray = [[NSMutableArray alloc] init];
    [self loadRequestData];
}

- (void)goReturn
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)loadRequestData
{
    NSDictionary *header = [AnalysisJson PackageJsonHeader:@"W113"];

    NSDictionary *body = [self PackageBody:0];
    NSData *requestJson = [AnalysisJson PackageJsonFromHeader:header andBody:body];
    
    NSLog(@"%@",requestJson);
    //发送报文
    [self getTableData: requestJson];
}

- (void)getTableData:(NSData *)data
{
    [MultiThreading getDataFromNetwork:[SERVICE_URL stringByAppendingString:@"QueryNewsBasic"] toObject:self callBack:@selector(requestCallBack:) withBody:data];
}

- (void)requestCallBack:(NSDictionary *)dic
{
    NSObject *body = dic[@"body"];
    NSLog(@"%@",[body class]);
    if([body isKindOfClass:[NSDictionary class]] && [(NSDictionary *)body objectForKey:@"news"] != nil)
    {
        self.dataarray = [(NSDictionary *)body objectForKey:@"news"];
    }
    
    [self.vedioTable reloadData];
}

- (NSDictionary *)PackageBody:(int)index
{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    dic[@"pageIndex"] = [NSString stringWithFormat:@"%d",index];
    dic[@"pageSize"] = [NSString stringWithFormat:@"%d",0];
    dic[@"cateId"] = [NSString stringWithFormat:@"%d",2];
    return dic;
}

//显示、隐藏tabbar add by chengxiang20130731
- (void)viewDidAppear:(BOOL)animated
{
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    UITabBarController *aController = (UITabBarController *)delegate.window.rootViewController;
    [delegate hideTabBar:aController];
}

- (void)viewDidDisappear:(BOOL)animated
{
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    UITabBarController *aController = (UITabBarController *)delegate.window.rootViewController;
    [delegate showTabBar:aController];
}

#pragma -
#pragma table property

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return  [self.dataarray count];
}


-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* strIdentity = @"customtableviewcell";
    
    CustomTableViewCell* cell = (CustomTableViewCell*)[tableView dequeueReusableCellWithIdentifier:strIdentity];
    
    
    if (cell == nil) {
        
//        cell = (CustomTableViewCell*)[[NSBundle mainBundle] loadNibNamed:@"CustomTableViewCell" owner:self options:nil];
        
        cell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strIdentity];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    
    //[tableView setSeparatorColor:[UIColor whiteColor]];
    
    //[cell setMovieURL:<#(NSString *)#>]
   // [cell setNetworkQueue:downloadQueue];
    [cell setDownloadPath:downloadPath];
  
    
    if([self.dataarray count] == 0)
    {
        return  cell;
    }
    
    NSDictionary* dict = [self.dataarray objectAtIndex:[indexPath row]];
    if(dict.count == 0)
    {
        return cell;
    }
    
    cell.vedioDesc = [NSString stringWithFormat:@"%@",[dict objectForKey:@"summary"]] ;
    cell.vediotitle=[NSString stringWithFormat:@"%@",[dict objectForKey:@"title"]];
    cell.vidioDate= [NSString stringWithFormat:@"%@",[dict objectForKey:@"posttime"]];
//    [cell setMovieComment:[NSString stringWithFormat:@"%@",[dict objectForKey:@"vedio"]]];
    cell.vediosource = [NSString stringWithFormat:@"%@",[dict objectForKey:@"video"]] ;
    [cell setParentViewController:self];
    
    [cell updateCommentAndPreview];
    return cell;
}

#pragma - tablecell height
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120.0;
}

#pragma -
#pragma 视频播放

-(void)readyPlay:(NSString*)vediourl
{
    moviePlayer = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:vediourl]];
    
    MPMoviePlayerController* player = [moviePlayer moviePlayer];
    if ([moviePlayer respondsToSelector:@selector(loadState:)])
    {
        
        [player setControlStyle:MPMovieControlStyleFullscreen];        //
        //满屏
        [player setFullscreen:YES];
        // 有助于减少延迟
        [player prepareToPlay];
        
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(moviePlayerLoadStateChanged:)
                                                     name:MPMoviePlayerLoadStateDidChangeNotification
                                                   object:nil];
    }
    else
    {
        
        [player play];
        [self presentMoviePlayerViewControllerAnimated:moviePlayer];
    }    
    //播放结束
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moviePlayerBackDidFinish:)
                                                 name:MPMoviePlayerPlaybackDidFinishNotification
                                               object:nil];
    
}

-(void)moviePlayerBackDidFinish:(NSNotification*)notification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
